package com.ccx.coachsite.ui.manage;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ccx.coachsite.R;
import com.ccx.coachsite.bus.Account;
import com.ccx.coachsite.bus.AccountMgr;
import com.ccx.coachsite.bus.CommonBus;
import com.ccx.coachsite.bus.CustomInfo;
import com.ccx.coachsite.bus.CustomMessage;
import com.ccx.coachsite.bus.ExpertMessage;
import com.ccx.coachsite.bus.SharedKey;
import com.ccx.coachsite.http.BaseResp;
import com.ccx.coachsite.http.BitmapProgress;
import com.ccx.coachsite.http.ProgressListener;
import com.ccx.coachsite.ui.login.TopViewUtil;
import com.ccx.coachsite.ui.own.OwerBaseView;
import com.ccx.coachsite.ui.own.OwerMainBase;
import com.ccx.coachsite.ui.own.OwerBaseView.LoadDataTask;
import com.ccx.coachsite.util.CommonViewUtils;
import com.ccx.coachsite.util.SharedPreferencesUtil;
import com.ccx.coachsite.util.StringUtil;
import com.ccx.coachsite.webimage.ImageLoader;

public class ManageMessageView extends OwerBaseView {

	private ListView lstMessages;
	private CustomMessage mApp;
	private CustomInfo mCustomInfo;
	private TextView inputText;
	private ManageMessageAdapter mAdapter;
	private View noneView;
	public ManageMessageView(Context context, OwerMainBase superView, Object customInfo) {
		super(context, superView);
		mCustomInfo = (CustomInfo)customInfo;
		loadData();
		TopViewUtil.updateTopTitle(mSuperView, R.id.login_top_title,  mCustomInfo.getName());
		
		inputText = (TextView)findViewById(R.id.manage_messnage_text);
		View sendButton = findViewById(R.id.manage_messnage_send_button);
		sendButton.setOnClickListener(new OnSendMessageListener());
		
		noneView = findViewById(R.id.custom_message_none_panel); 
		TextView tvInfo = (TextView)noneView.findViewById(R.id.ower_none_title);
		tvInfo.setText("目前没有消息记录");
	}
	
	public  void refreshMessageData(String users) {
		if(users == null)
			return;
		
		if(users.indexOf(mCustomInfo.getId() + "") < 0)
			return;
		
		if (isBusy)
			return;
		isBusy = true;
		
		LoadDataTask task = new LoadDataTask();
		task.execute(0);
	}

	class OnSendMessageListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			sendMessageBus bus = new sendMessageBus(mContext);
			String message = inputText.getText().toString();
			String userId = SharedPreferencesUtil.getValue(mContext,
					SharedKey.Shared_UserId_Key, "");
			if (TextUtils.isEmpty(message)) {
				Toast.makeText(mContext, "请输入消息内容", Toast.LENGTH_SHORT)
						.show();
			} else if (message.length() > 280) {
				Toast.makeText(mContext, "消息内容长度不得大于 280", Toast.LENGTH_SHORT)
						.show();
			} else {
				bus.setSendMessageParam(userId, mCustomInfo.getId()+"", message);
				bus.doTask();
			}
//			if(!StringUtil.isEmpty(message))
//			{
//				bus.setSendMessageParam(userId, mCustomInfo.getId()+"", message);
//				bus.doTask();
//			}
			CommonViewUtils.hideKeyboard((Activity)mContext);
		}
	}
	
	protected boolean onLoadData() {
		Account act = AccountMgr.readAccountInfo(mContext);
		mApp = ManageProvider.getInstance().getCustomMessage(mContext, act, mCustomInfo);
		if(mApp == null)
		{
			/*
			mApp = new CustomMessage();
			mApp.setIcon("http://www.cnnb.com.cn/pic/0/00/47/88/478836_744557.jpg");
			mApp.setAppCount(1);
			mApp.setTurCount(2);
			
			List<ExpertMessage> lstMessage = new ArrayList<ExpertMessage>();
			ExpertMessage info = new ExpertMessage();
			info.setId(1);
			info.setContent("message1");
			info.setTime("messageTime1");
			info.setCreator("我");
			info.setIcon("http://www.cnnb.com.cn/pic/0/00/47/88/478836_744557.jpg");
			lstMessage.add(info);
			
			info = new ExpertMessage();
			info.setId(2);
			info.setContent("message2");
			info.setTime("messageTime2");
			info.setCreator("22");
			info.setIcon("http://www.xiancn.com/img/2009-08/31/xin_290806310816059165138.jpg");
			lstMessage.add(info);
			
			mApp.setLstMessage(lstMessage);
			*/
			return false;
		}
		return true;
	}

	protected void doRefreshDataSuccess() 
	{
		View btn = mCustomInfo.getMessageBtn();
		if(btn != null)
		{
			//btn.setText("0条未读");
			btn.setVisibility(View.INVISIBLE);
		}
		TextView appNum = (TextView) findViewById(R.id.message_app_collect_count);
		TextView turNum = (TextView) findViewById(R.id.message_tur_collect_count);
		
		appNum.setText("应用收藏: "+mApp.getAppCount());
		turNum.setText("文章收藏: "+mApp.getTurCount());
		ImageView imgV =  (ImageView) findViewById(R.id.manager_message_person_icon);
		imgV.setImageResource(R.drawable.ower_image_none);
		ImageLoader.loadBitmap(mApp.getIcon(), imgV);
		
		lstMessages = (ListView) 
				findViewById(R.id.manage_message_list);
		
		List<ExpertMessage> lstMessage = mApp.getLstMessage();
		if(lstMessage.size() == 0)
		{
			noneView.setVisibility(View.VISIBLE);
			lstMessages.setVisibility(View.GONE);
		}
		else
		{
			noneView.setVisibility(View.GONE);
			lstMessages.setVisibility(View.VISIBLE);
		}
		if(mAdapter != null)
			mAdapter = null;
		mAdapter = new ManageMessageAdapter(lstMessage);
		lstMessages.setAdapter(mAdapter);
		
		
	}
	
	private void onSendMessage()
	{
		inputText.setText("");
		loadDataWithoutLoading();
	}
	
	class sendMessageBus extends CommonBus{

		public sendMessageBus(Context context) {
			super(context);
		}
		
		@Override
		public void callBack(int taskType, BaseResp response, String responseJson) {
			super.callBack(taskType, response, responseJson);
			
			if(response.isSuccess())
			{
				onSendMessage();
			}
			else
			{

			}
		}
	}
	
	class ManageMessageAdapter extends BaseAdapter {

		private List<ExpertMessage> messages;
		private Bitmap myPhoto, herPhoto;
		private boolean loadingMyPhoto, loadingHerPhoto;

		public ManageMessageAdapter(List<ExpertMessage> messages) {
			this.messages = messages;
		}

		@Override
		public int getCount() {
			return messages.size();
		}

		@Override
		public Object getItem(int position) {
			return messages.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
		
		public boolean IsShowTime(int position)
		{
			if(position <= 0)
				return true;
			
			String strMt1= ((ExpertMessage) getItem(position)).getTime();
			String strMt2= ((ExpertMessage) getItem(position - 1)).getTime();
			
			if(StringUtil.isEmpty(strMt1) || strMt1.equals("null"))
				return false;
			
			if(StringUtil.isEmpty(strMt2) || strMt2.equals("null"))
				return true;
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
			//得到指定模范的时间 
			Date d1 = null;
			Date d2 = null;
			try {
				d1 = sdf.parse(strMt1);
				d2 = sdf.parse(strMt2);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(d1 == null || d2 == null)
				return true;
			
			long min = Math.abs(((d1.getTime() - d2.getTime())/(60*1000)));
			
			if(min <= 5)
				return false;
			
			return true;
		}
		
		private void loadMyPhoto(String url) {
			if(StringUtil.isEmpty(url) || url.equals("null"))
				return;
			if (loadingMyPhoto)
				return;
			loadingMyPhoto = true;
			myPhoto = ImageLoader.loadBitmap(url,
					new ProgressListener<BitmapProgress>() {

						@Override
						public void onProgressUpdate(BitmapProgress entity) {

						}

						@Override
						public void onPostExecute(BitmapProgress entity) {
							myPhoto = entity.getBitmap();
							ManageMessageAdapter.this.notifyDataSetInvalidated();
						}
					});
		}

		private void loadHerPhoto(String url) {
			if(StringUtil.isEmpty(url) || url.equals("null"))
				return;
			
			if (loadingHerPhoto)
				return;
			loadingHerPhoto = true;
			herPhoto = ImageLoader.loadBitmap(url,
					new ProgressListener<BitmapProgress>() {

						@Override
						public void onProgressUpdate(BitmapProgress entity) {

						}

						@Override
						public void onPostExecute(BitmapProgress entity) {
							herPhoto = entity.getBitmap();
							ManageMessageAdapter.this.notifyDataSetInvalidated();
						}
					});
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ExpertMessage message = (ExpertMessage) getItem(position);
			View view = null;
			LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			view = convertView != null ? convertView : mInflater.inflate(R.layout.expert_message_item, parent,  false);
			ImageView imgPhoto = null;
			//ImageView imgPhoto = (ImageView) view
			//		.findViewById(R.id.expert_message_photo);
			ImageView myPhotoView = (ImageView) view
					.findViewById(R.id.expert_message_photo);
			ImageView herPhotoView = (ImageView) view
					.findViewById(R.id.expert_her_message_photo);
			TextView txtCreator = (TextView) view
					.findViewById(R.id.expert_message_creator);
			TextView txtTime = (TextView) view
					.findViewById(R.id.expert_message_time);
			TextView txtContent = (TextView) view
					.findViewById(R.id.expert_message_content);
			View layout = view.findViewById(R.id.expert_message_content_layout);
			if (message.isCreateBySelf()) {
				herPhotoView.setVisibility(View.GONE);
				myPhotoView.setVisibility(View.VISIBLE);
				layout.setBackgroundResource(R.drawable.expert_message_me);
				layout.setPadding(4, 0, 4, 2);
				// ImageLoader.loadBitmap(message.getIcon(), myPhotoView);
				if (myPhoto != null)
					myPhotoView.setImageBitmap(myPhoto);
				else
					loadMyPhoto(message.getIcon());
			} else {
				myPhotoView.setVisibility(View.GONE);
				herPhotoView.setVisibility(View.VISIBLE);
				layout.setBackgroundResource(R.drawable.expert_message_she);
				layout.setPadding(4, 0, 4, 2);
				// ImageLoader.loadBitmap(message.getIcon(), herPhotoView);
				if (herPhoto != null)
					herPhotoView.setImageBitmap(herPhoto);
				else
					loadHerPhoto(message.getIcon());
			}
			if (!IsShowTime(position))
				txtTime.setVisibility(View.GONE);
			else
				txtTime.setVisibility(View.VISIBLE);
			txtCreator.setText(message.getCreator());
			txtTime.setText(message.getTime());
			txtContent.setText(message.getContent());
			return view;
		}
	}

}
